package com.shaoshaohuo.app.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.AccountDetailEntity;
import com.shaoshaohuo.app.entity.AccountDetailEntity.AccountDetail;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.BaseUserInfo;
import com.shaoshaohuo.app.entity.CheckPayPwdEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.AddressManagerActivity;
import com.shaoshaohuo.app.ui.MyEvaluationActivity;
import com.shaoshaohuo.app.ui.MyInfoActivity;
import com.shaoshaohuo.app.ui.PayAccountActivity;
import com.shaoshaohuo.app.ui.WithdrawForAccountActivity;
import com.shaoshaohuo.app.utils.sharesdk.ShareContent;
import com.shaoshaohuo.app.utils.sharesdk.ShareFactory;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.CouponActivity;
import com.shaoshaohuo.app.ui.IncomeStatementActivity;
import com.shaoshaohuo.app.ui.LoginActivity;
import com.shaoshaohuo.app.ui.MyPointsActivity;
import com.shaoshaohuo.app.ui.PayManageActivity;
import com.shaoshaohuo.app.ui.SettingActivity;
import com.shaoshaohuo.app.ui.ec.EcBrowseRecordActivity;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.wxapi.RechangeActivity;

import cn.sharesdk.framework.Platform.ShareParams;

/**
 * 我的
 *
 * @author cao
 */
public class MyInfoFragment extends Fragment implements OnClickListener {

    private View mContentView;
    private TopbarView mTopbarView;
    private String mArgument;
    public static final String ARGUMENT = "argument";
    private ImageView mHeadView;
    private TextView mOverageView;
    private TextView mPrepaidView;
    private TextView mMoneyView;
    private AccountDetail data;
    private LinearLayout mMoneyDetilView;
    private LinearLayout mPayPasswordView;
    private LinearLayout mCouponView;
    private LinearLayout mMyPointsView;
    private LinearLayout mBrowseRecord;
    private LinearLayout mShareAppView;
    private TextView mPayPasswordTextView;

    private LinearLayout ll_pay_account;//1.8

    private LinearLayout ll_my_address; // 1.8.2
    private LinearLayout ll_my_comment; // 1.8.2

    private ImageView iv_name;
    private ImageView iv_car;

    private TextView tv_modify_info;
    private TextView tv_name;

    private  LinearLayout ll_user_info;

    private boolean isHavePasswd = false;

    public static MyInfoFragment newInstance(String argument) {
        Bundle bundle = new Bundle();
        bundle.putString(ARGUMENT, argument);
        MyInfoFragment contentFragment = new MyInfoFragment();
        contentFragment.setArguments(bundle);
        return contentFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null)
            mArgument = bundle.getString(ARGUMENT);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (mContentView == null) {
            mContentView = inflater.inflate(R.layout.fragment_my_info, null);

            initView();
            setUpView();
            requestData();
//			getAccountDetail();
        } else {
            ViewGroup parent = (ViewGroup) mContentView.getParent();
            if (parent != null) {
                parent.removeView(mContentView);
            }
        }
//        View viewById=mContentView.findViewById(R.id.topbar);

        return mContentView;
    }

    private void requestData() {
        if (AccountManager.isLogin()) {
            BaseUserInfo userInfo = AccountManager.getUserInfo();
            if (userInfo != null) {
                String authStatus = AccountManager.getUserAuthStatus();
                ImageLoader.getInstance().displayImage(userInfo.getAvatar(), mHeadView,
                        ImageLoadUtil.getDisplayImageOptions(R.drawable.pic_head_ad, 180));
                getAccountDetail();

                initModifyPassword();

                tv_name.setText(userInfo.getRealname());


            }
        } else {
            mOverageView.setText("未登录");
        }

    }

    /**
     * 判断是否设置了 支付密码
     */
    private void initModifyPassword() {
        String isHavePasswd = SharedPreferencesHelper.getString("isHavePasswd", "-1");

        if ("1".equals(isHavePasswd)) {
            isSetPassword();
        } else if ("0".equals(isHavePasswd)) {
            isNoSetPassword();
        } else if ("-1".equals(isHavePasswd)) {
            RequestService.getInstance().checkPayPwd(getActivity(), CheckPayPwdEntity.class, new RequestListener() {
                @Override
                public void onSuccess(int requestCode, BaseEntity resultData) {
                    if (resultData.isOk()) {
                        CheckPayPwdEntity entity = (CheckPayPwdEntity) resultData;
                        String isset = entity.getData().getIsset();
                        if ("1".equals(isset)) {
                            isSetPassword();
                        } else if ("0".equals(isset)) {
                            isNoSetPassword();
                        }
                        SharedPreferencesHelper.setString("isHavePasswd", isset);
                    }
                }

                @Override
                public void onFailed(int requestCode, Exception error, String msg) {
                }
            });
        }
    }

    //如果设置了支付密码
    public void isSetPassword() {
        mPayPasswordTextView.setText("修改支付密码");
        isHavePasswd = true;
    }

    //如果没有设置支付密码
    public void isNoSetPassword() {
        mPayPasswordTextView.setText("设置支付密码");
        isHavePasswd = false;
    }

    private void initView() {
        mTopbarView = (TopbarView) mContentView.findViewById(R.id.topbar);
        mTopbarView.setCenterText("我的");
        mTopbarView.setLeftView(false, false);
        mTopbarView.setRightImage(R.drawable.icon_set_white_ad);
        mTopbarView.setRightClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), SettingActivity.class));
            }
        });

        mHeadView = (ImageView) mContentView.findViewById(R.id.iv_head);
        mOverageView = (TextView) mContentView.findViewById(R.id.tv_overage);
        mPrepaidView = (TextView) mContentView.findViewById(R.id.tv_prepaid);
        mMoneyView = (TextView) mContentView.findViewById(R.id.tv_money);
        mMoneyDetilView = (LinearLayout) mContentView.findViewById(R.id.ll_money_detil);
        mPayPasswordView = (LinearLayout) mContentView.findViewById(R.id.ll_pay_password);
        mPayPasswordTextView = (TextView) mContentView.findViewById(R.id.tv_pay_password);
        mCouponView = (LinearLayout) mContentView.findViewById(R.id.ll_coupon);
        mMyPointsView = (LinearLayout) mContentView.findViewById(R.id.ll_my_points);
        mBrowseRecord = (LinearLayout) mContentView.findViewById(R.id.ll_browse_record);
        mShareAppView = (LinearLayout) mContentView.findViewById(R.id.ll_share_app);

        ll_pay_account = (LinearLayout) mContentView.findViewById(R.id.ll_pay_account);//1.8

        ll_my_address = (LinearLayout) mContentView.findViewById(R.id.ll_my_address); // 1.8.2
        ll_my_comment = (LinearLayout) mContentView.findViewById(R.id.ll_my_comment);

        tv_modify_info = (TextView) mContentView.findViewById(R.id.tv_modify_info);
        tv_name = (TextView) mContentView.findViewById(R.id.tv_name);

        ll_user_info = (LinearLayout) mContentView.findViewById(R.id.ll_user_info);

        iv_name = (ImageView) mContentView.findViewById(R.id.iv_name);
        iv_car = (ImageView) mContentView.findViewById(R.id.iv_car);
    }

    private void setUpView() {
        mPrepaidView.setOnClickListener(this);
        mMoneyView.setOnClickListener(this);
        mMoneyDetilView.setOnClickListener(this);
        mPayPasswordView.setOnClickListener(this);
        mCouponView.setOnClickListener(this);
        mMyPointsView.setOnClickListener(this);
        mBrowseRecord.setOnClickListener(this);
        mShareAppView.setOnClickListener(this);

        ll_pay_account.setOnClickListener(this);
        ll_my_address.setOnClickListener(this);
        ll_my_comment.setOnClickListener(this);
        tv_modify_info.setOnClickListener(this);
        ll_user_info.setOnClickListener(this);


        SpannableString span = new SpannableString("0.00元");
        span.setSpan(new AbsoluteSizeSpan(13, true), span.length() - 1, span.length(), SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);
        mOverageView.setText(span);

        if (!AccountManager.isUserAuth()) {
            iv_name.setVisibility(View.GONE);
            iv_car.setVisibility(View.GONE);
        }else if(!AccountManager.isCarAuth()){
            iv_car.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_prepaid:
                startActivity(new Intent(getActivity(), RechangeActivity.class));
                break;
            case R.id.tv_money:
                if (data != null) {
                    Intent intent = new Intent(getActivity(), WithdrawForAccountActivity.class);
                    intent.putExtra(ExtraName.freetotal, data.getFreetotal());
                    startActivity(intent);
                } else {
                    ((BaseActivity) getActivity()).showToast(R.string.please_check_network);
                }
                break;
            case R.id.ll_money_detil:
                startActivity(new Intent(getActivity(), IncomeStatementActivity.class));
                break;
            case R.id.ll_pay_password:
                Intent intent = new Intent(getActivity(), PayManageActivity.class);
                intent.putExtra(ExtraName.isHavePasswd, isHavePasswd);
                startActivity(intent);
                break;
            case R.id.ll_coupon:
                startActivity(new Intent(getActivity(), CouponActivity.class));
                break;
            case R.id.ll_share_app:
            /*Intent generalizeIntent = new Intent(getActivity(), MyGeneralizeActivity.class);
			generalizeIntent.putExtra(ExtraName.shareType, MyGeneralizeActivity.SHARE_TYPE_APP);
			startActivity(generalizeIntent);*/
                ShareParams params = new ShareParams();
                params.setTitle(ShareContent.SHARE_APP_CONTENT);
                params.setTitleUrl(HttpConfig.WebPage.SHARE);
                params.setText(ShareContent.SHARE_APP_CONTENT);
                params.setImageUrl(HttpConfig.WebPage.SHARE_IMAGE_PATH);
                params.setUrl(HttpConfig.WebPage.SHARE);
                ShareFactory.showShare(getActivity(), params);
                break;
            case R.id.ll_my_points:
                if (AccountManager.isLogin()) {
                    startActivity(new Intent(getActivity(), MyPointsActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.ll_browse_record:
                if (AccountManager.isLogin()) {
                    startActivity(new Intent(getActivity(), EcBrowseRecordActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.ll_pay_account:
                startActivity(new Intent(getActivity(), PayAccountActivity.class));
                break;
            case R.id.ll_my_address:
                startActivity(new Intent(getActivity(), AddressManagerActivity.class));
                break;
            case R.id.ll_my_comment:
                if (AccountManager.isLogin()) {
                    startActivity(new Intent(getActivity(), MyEvaluationActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.ll_user_info:
            case R.id.tv_modify_info:
                    startActivity(new Intent(getActivity(), MyInfoActivity.class));
                break;
        }
    }

    /**
     * 请求网络获得账户详情
     */
    private void getAccountDetail() {
        ((BaseActivity) getActivity()).startLoadingDialog();
        RequestService.getInstance().getAccountDetail(getActivity(), AccountDetailEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                ((BaseActivity) getActivity()).dismissLoadingDialog();
                if (resultData.isOk()) {
                    AccountDetailEntity entity = (AccountDetailEntity) resultData;
                    updateUi(entity);
                } else {
                    ((BaseActivity) getActivity()).showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                BaseActivity activity = (BaseActivity) getActivity();
                if (activity != null) {
                    activity.dismissLoadingDialog();
                    activity.showToast(R.string.please_check_network);
                }
            }
        });
    }

    /**
     * 根据账户详情 填充账务余额
     *
     * @param entity
     */
    protected void updateUi(AccountDetailEntity entity) {
        data = entity.getData();

//		mOverageView.setText(Data.getFreetotal());
        SpannableString span = new SpannableString(data.getFreetotal() + "元");
        span.setSpan(new AbsoluteSizeSpan(13, true), span.length() - 1, span.length(), SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);
        mOverageView.setText(span);
    }

    /* (non-Javadoc)
     * @see android.support.v4.app.Fragment#onResume()
     */
    @Override
    public void onResume() {
        super.onResume();
        requestData();
    }


}
